package com.cyzy.controller;

import com.cyzy.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/buy")
public class BuyController {

    @Autowired// 注入Redis  Key value键值对
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/buy")
    public R buy(@RequestParam("acc") String acc) {
        String accKey = "buy-acc-activecode";

        String key = "buy-题库id-activecode";
        String code = redisTemplate.opsForList().leftPop(key);
        if(code != null){
            long re = redisTemplate.opsForSet().add(accKey, acc);
            if(re == 0){    //已经存在  买过了 ，退回
                redisTemplate.opsForList().leftPush(key, code);
                return R.ok().code(500).message("已经购买过，不能重复购买");
            }else {
                //没有高并发，抢购10个，只有10次
                //下单操作，生成订单
                return R.ok().code(200).message("恭喜抢购成功，激活码：" + code);
            }
        }else {
            return R.ok().code(500).message("很遗憾，手速慢了，抢购失败");
        }
    }

}
